package cn.accjiyun.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by jiyun on 2017/11/2.
 */
public class ParamUtil {

    /**
     * 将请求参数用URL格式编码
     * @param params 参数键值对
     * @return 编码后URL字符串
     */
    public static String paramsToURL(Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return null;
        }
        String[] sortedKeys = params.keySet().toArray(new String[] {});
        Arrays.sort(sortedKeys);

        StringBuilder paramString = new StringBuilder();
        boolean first = true;
        for (String key : sortedKeys) {
            Object val = params.get(key);
            if (!first) {
                paramString.append("&");
            }
            if (val instanceof String) {
                try {
                    paramString.append(URLEncoder.encode(key, "UTF-8"));
                    if (val != null) {
                        String strValue = (String) val;
                        paramString.append("=").append(
                                URLEncoder.encode(strValue, "UTF-8"));
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            first = false;
        }
        return paramString.toString();
    }

}
